package boot.example.tcp.server.netty.codec;


import boot.example.tcp.server.consts.NettyConstants;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

/**
 * 编码器-GBK编码
 *
 * @Author guoyb
 * @Date 2023/9/28  16:44
 */
public class NettyEncoder extends MessageToByteEncoder<String> {

    // ObjectEncoder 将对象（需要实现Serializable接⼝）编码为字节流
    // SocksMessageEncoder 将SocksMessage编码为字节流
    // HAProxyMessageEncoder 将HAProxyMessage编码成字节流


    @Override
    protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out) throws Exception {
        byte[] byteMsg = msg.getBytes(NettyConstants.CHARSET_GBK);
        int msgLength = byteMsg.length;
        ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer(4 + byteMsg.length);
        buf.writeInt(msgLength);
        buf.writeBytes(byteMsg);
        out.writeBytes(buf);
        buf.release();
    }
}

